#!/usr/bin/env node

const express = require('express');
const crypto = require('crypto');
const { program } = require('commander');
const MaddyService = require('./service');
const fs = require('fs');
const path = require('path');
const prettyjson = require('prettyjson');

// 初始化服务
const maddyService = new MaddyService();
const PASS_FILE = path.join(__dirname, 'pass');

// 密钥初始化函数
const initializeApiKey = () => {
  try {
    if (!fs.existsSync(PASS_FILE)) {
      const key = crypto.randomBytes(32).toString('hex');
      fs.writeFileSync(PASS_FILE, key, { mode: 0o600 });
      console.log('已创建新密钥文件:', PASS_FILE);
      console.log('你的API密钥是:', key);
      console.log('请妥善保存此密钥！');
      return key;
    }
    
    const existingKey = fs.readFileSync(PASS_FILE, 'utf8').trim();
    if (!existingKey) {
      throw new Error('密钥文件存在但为空');
    }
    return existingKey;
  } catch (err) {
    console.error('密钥文件处理失败:', err);
    process.exit(1);
  }
};

// CLI 命令处理
function setupCLI() {
  program
    .name('mactl')
    .description('Maddy 邮件用户管理命令行工具')
    .version('1.0.0');

  // 添加用户命令
  program.command('add <username>')
    .description('添加新用户')
    .action((username) => {
      try {
        const result = maddyService.addUser(username);
        console.log('用户创建成功:');
        console.log(`邮箱: ${result.email}`);
        console.log(`密码: ${result.password}`);
      } catch (error) {
        console.error('添加用户失败:', error.message);
        process.exit(1);
      }
    });

  // 删除用户命令
  program.command('del <username>')
    .description('删除用户')
    .action((username) => {
      try {
        const email = maddyService.deleteUser(username);
        console.log(`用户已删除: ${email}`);
      } catch (error) {
        console.error('删除用户失败:', error.message);
        process.exit(1);
      }
    });

  // 列出用户命令
  program.command('list')
    .description('列出所有用户')
    .action(() => {
      try {
        const users = maddyService.listUsers();
        console.log('用户列表:');
        users.forEach(user => console.log(`- ${user}`));
        console.log(`\n总计: ${users.length} 个用户`);
      } catch (error) {
        console.error('列出用户失败:', error.message);
        process.exit(1);
      }
    });

  program.parse(process.argv);
}

// Web API 服务
function startWebServer() {
  const app = express();
  const port = 8899;
  const API_KEY = initializeApiKey();

  app.set('json spaces', 2);
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));

  // 认证中间件
  const authMiddleware = (req, res, next) => {
    const clientKey = req.query.key;
    
    if (!clientKey) {
      return res.status(401).json({
        success: false,
        error: "MISSING_API_KEY",
        message: '请求缺少API密钥',
        solution: '请在URL中添加key参数，例如 ?key=你的密钥'
      });
    }
    
    if (clientKey !== API_KEY) {
      return res.status(403).json({
        success: false,
        error: "INVALID_API_KEY",
        message: '提供的API密钥无效',
        solution: '请检查密钥是否正确或联系管理员'
      });
    }
    
    next();
  };

  // API路由
  app.get('/', authMiddleware, (req, res) => {
    const { add, del, list, pretty } = req.query;

    const sendResponse = (data) => {
      if (pretty) {
        res.type('text').send(
          prettyjson.render(data, {
            keysColor: 'cyan',
            dashColor: 'magenta',
            stringColor: 'white',
            numberColor: 'yellow'
          })
        );
      } else {
        res.json(data);
      }
    };

    try {
      if (add) {
        const result = maddyService.addUser(add);
        sendResponse({
          success: true,
          message: `用户已创建: ${result.email}`,
          email: result.email,
          password: result.password
        });
      } else if (del) {
        const email = maddyService.deleteUser(del);
        sendResponse({
          success: true,
          message: `用户已删除: ${email}`
        });
      } else if (list) {
        const users = maddyService.listUsers();
        sendResponse({
          success: true,
          data: {
            count: users.length,
            users: users.sort()
          }
        });
      } else {
        sendResponse({
          success: false,
          error: "INVALID_REQUEST",
          message: '无效的请求参数',
          usage: {
            add: '/?key=API_KEY&add=用户名',
            del: '/?key=API_KEY&del=用户名',
            list: '/?key=API_KEY&list=true',
            pretty: '添加 &pretty=true 获取彩色输出'
          }
        });
      }
    } catch (error) {
      console.error('API处理错误:', error);
      sendResponse({
        success: false,
        error: "SERVICE_ERROR",
        message: error.message,
        details: process.env.NODE_ENV === 'development' ? error.stack : undefined
      });
    }
  });

  app.listen(port, () => {
    console.log(`
    ============================================
    Maddy 用户管理 API 服务已启动
    访问地址: http://localhost:${port}
    示例请求: curl http://localhost:${port}/?key=${API_KEY}&list=true
    ============================================
    `);
  });
}

// 判断运行模式
if (require.main === module) {
  // 检查是否以 CLI 模式运行
  if (process.argv.length > 2 && !process.argv[1].includes('mocha')) {
    setupCLI();
  } else {
    startWebServer();
  }
}

// 错误处理
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常:', err);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的拒绝:', promise, '原因:', reason);
});

